﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using NHibernate;

using NHibernate.Criterion;
using NHibernate.Linq;
using Ornament.NHibernates;

namespace Ornament.MemberShip.Dao.NHibernateImple
{
    public class UserGroupDao : DaoBase<Guid, UserGroup>, IUserGroupDao
    {
        #region IUserGroupDao Members
        public IQueryable<UserGroup> UserGroups
        {
            get { return SessionManager.Instance.CurrentSession.Query<UserGroup>(); }
        }

        public ReadOnlyCollection<UserGroup> GetUserGroupByUser(string userLoginId)
        {
            IQuery query = CreateQuery("Select elements(u.UserGroups) from User u where u.LoginId=?");
            query.SetString(0, userLoginId);

            return new ReadOnlyCollection<UserGroup>(query.List<UserGroup>());
        }

        public ReadOnlyCollection<UserGroup> GetUnuseGroup(string loginId)
        {
            IQuery query =
                CreateQuery(
                    "From UserGroup ug where ug not in(Select elements(u.UserGroups) from User u where u.LoginId=?)");
            query.SetString(0, loginId);

            return new ReadOnlyCollection<UserGroup>(query.List<UserGroup>());
        }

        public IList<UserGroup> GetUserGroups(Guid[] guids)
        {
            if (guids == null || guids.Length == 0)
                return new ReadOnlyCollection<UserGroup>(new List<UserGroup>());

            ICriteria ica = CreateCriteria().Add(Restrictions.In("Id", guids));
            return new ReadOnlyCollection<UserGroup>(ica.List<UserGroup>());
        }

        public void Delete(Guid[] ids)
        {
            var builder = new StringBuilder("From UserGroup ug where ug in (");
            bool isFirst = true;
            foreach (Guid id in ids)
            {
                if (!isFirst)
                {
                    builder.Append(",");
                }
                else
                {
                    isFirst = false;
                }
                builder.Append("'" + id + "'");
            }
            builder.Append(")");
            CurrentSession.Delete(builder.ToString());
        }

        #endregion

        protected override Order[] DefaultOrder
        {
            get
            {
                return new Order[] { Order.Asc("Name") };
            }
        }
    }
}